<template>
  <el-form
    ref="loginFormRef"
    :model="loginForm"
    :rules="loginRules"
    size="large"
  >
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" placeholder="请输入用户名">
        <template #prefix>
          <el-icon class="el-input__icon">
            <user />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input
        v-model="loginForm.password"
        type="password"
        placeholder="请输入密码"
        show-password
        autocomplete="new-password"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <lock />
          </el-icon>
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="login-btn">
    <el-button
      :icon="CircleClose"
      round
      size="large"
      @click="resetForm(loginFormRef)"
    >
      重置
    </el-button>
    <el-button
      :icon="UserFilled"
      round
      size="large"
      type="primary"
      :loading="loading"
      @click="login()"
    >
      登录
    </el-button>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElIcon,
  ElInput,
  ElNotification,
  FormInstance,
} from "element-plus";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import { loginApi } from "@/api/modules/index";
import { initDynamicRouter } from "@/router/modules/dynamicRouter";
import { HOME_URL } from "@/config";
import { getTimeState } from "@/utils";
import { useUserStore } from "@/stores/modules/user";
import { useRouter } from "vue-router";
import { useMenuStore } from "@/stores/modules/menu";
import { Login } from "@/api/interface";
import { useTheme } from "@/hooks/useTheme";
import { useGlobalStore } from "@/stores/modules/global";

const router = useRouter();
const userStore = useUserStore();
const authStore = useMenuStore();
const globalStore = useGlobalStore();
const { changePrimary } = useTheme();
const loginForm: Login.ReqLoginForm = reactive({
  username: "sq",
  password: "123456",
  encrypttype: 0,
});
const loading = ref(false);
// type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});
// const remenberP = ref(false);

/**
 * @use 记住密码事件
 */
// const changeRemenber = (e: boolean) => {
//   remenberP.value = e;
//   console.log("11", remenberP.value);
//   // console.log(this.remenberP);
// };
const login = async () => {
  if (!loginFormRef.value) return;
  loginFormRef.value.validate(async (valid) => {
    if (!valid) return;
    loading.value = true;
    try {
      // const res = await loginApi(loginForm);

      userStore.setToken("sqtoken");
      // userStore.setUserInfo({ token: "sqtoken" });
      await authStore.getAuthMenuList();

      // 2.添加动态路由
      await initDynamicRouter();

      // 4.跳转到首页
      router.push(HOME_URL);
      ElNotification({
        title: getTimeState(),
        message: "欢迎登录",
        type: "success",
        duration: 3000,
      });
      localStorage.setItem(
        "userInfo",
        JSON.stringify({
          username: loginForm.username,
          password: window.btoa(loginForm.password),
        })
      );
    } catch (error) {
      console.log("出错啦=>", error);
    } finally {
      loading.value = false;
    }
  });
};

onMounted(() => {
  changePrimary(globalStore.primary);
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    e = (window.event as KeyboardEvent) || e;
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login();
    }
  };
});
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
